package com.bit.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.bit.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-11-22
 * Time: 16:17
 */

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;


    private final static Long VALID_TIME = 3660 * 1000L;

    @RequestMapping("/getCaptcha")
    //需要把内容写到浏览器里面，那就需要response
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/png");
//        response.setCharacterEncoding("utf-8");
        response.setHeader("Progna", "No-cache");

        //生成验证码
        try {
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code = captcha.getCode();
            session.setAttribute(captchaProperties.getSession().getKey(), code);
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());

            //这里是什么意思？
            captcha.write(response.getOutputStream());


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *验证用户输入的验证码是否正确
     * @param captcha :用户输入的验证码
     * @param session：
     * @return
     */
    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        String code = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date)session.getAttribute((captchaProperties.getSession().getDate()));
        if(captcha.equalsIgnoreCase(code) || System.currentTimeMillis() - date.getTime() < VALID_TIME){
            return true;
        }
        return false;
    }
}
